package com.fingard.dsp.bank.directbank.spdb01.authforrec;

public class XMLHelper {
    public static String formater(String xml) {
        StringBuffer resultBuffer = new StringBuffer();

        xml = xml.replaceAll("[ \n\t\f]+", " ");
        StringBuffer xmlBuffer = new StringBuffer(xml);
        int len = xmlBuffer.length();
        // start <
        // end </ or />
        int tabNum = -1;
        char ch = 0;
        for (int i = 0; i < len; i++) {
            ch = xmlBuffer.charAt(i);
            // </
            if (ch == '<' && i + 1 < len && xmlBuffer.charAt(i + 1) == '/') {
                tabNum--;
                i++;
                if (i - 2 > -1 && xmlBuffer.charAt(i - 2) == '>') {
                    resultBuffer.append("\n" + tabStr(tabNum));
                }
                resultBuffer.append("</");
                continue;
            }

            // />
            if (ch == '/' && i + 1 < len && xmlBuffer.charAt(i + 1) == '>') {
                tabNum--;
                i++;
                resultBuffer.append("/>");
                continue;
            }

            // <
            if (ch == '<') {
                resultBuffer.append("\n" + tabStr(tabNum));
                resultBuffer.append('<');
                tabNum++;
                continue;
            }

            resultBuffer.append(ch);
        }
        return resultBuffer.toString();
    }

    private static String tabStr(int num) {
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < num; i++) {
            str.append("  ");
        }
        return str.toString();
    }
}
